package com.waypolice.manager.component;

import com.waypolice.common.constant.VolItemConstant;
import com.waypolice.common.ftp.FTPClientForMount;
import com.waypolice.common.utils.*;
import com.waypolice.manager.service.CmsSinItemService;
import com.waypolice.manager.service.VolAndItemService;
import com.waypolice.pojo.CmsJudItem;
import com.waypolice.pojo.CmsSinItem;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 描述:
 *
 * @author zyp
 * @description 本地上传文件线程
 * @create 2019-06-21 15:31
 */
public class AddressUploadThread extends Thread {

    //当前用户上传的状态  用户账号——文件上传结束时间
    public static Map<String,Date> userUploadStatus = new HashMap<>();

    private static Properties properties = ReadProperties.getProperties("parameter.properties");

    private static Logger logger = LoggerFactory.getLogger(FTPClientForMount.class);

    private String FTPIp;

    private String FTPPort;

    private String FTPUser;

    private String FTPPassword;

    private String FTPPath;

    private String localAddress;

    private String fileId;

    private String type;

    private String userName;

    @Override
    public void run() {
        try {
            VolAndItemService volAndItemService = (VolAndItemService) ApplicationContextUtil.getBean(VolAndItemService.class);
            CmsSinItemService cmsSinItemService = (CmsSinItemService) ApplicationContextUtil.getBean(CmsSinItemService.class);
            //根据ftpIp是否为空判断 挂接文件的形式为ftp还是本地
            if(StringUtils.isNotBlank(FTPIp)){
                String IMAGE_SERVER_URL = properties.getProperty("IMAGE_SERVER_URL");
                String downArr = FileUtils.getFileMountWay();
                boolean isDownloadFile;
                //ftp形式上传
                FTPClientForMount ftpClientForMount = new FTPClientForMount(FTPIp,FTPPort,FTPUser,FTPPassword);
                //文件下载下来的文件
                File downFile ;
                boolean isConnect = false;
                switch (type){
                    //如果是卷
                    case VolItemConstant.FILE_TYPE_VOL:
                        String[] ids = fileId.split(",");
                        List<CmsJudItem> cmsJudItems = volAndItemService.selectAllByVolIds(Arrays.asList(ids));
                        for (CmsJudItem cmsJudItem : cmsJudItems){
                            if(ftpClientForMount.ftpClient==null||!ftpClientForMount.ftpClient.isConnected()){
                                isConnect = ftpClientForMount.initFTPClient();
                                if(!isConnect){
                                    logger.info("----FTP连接失败，终止下载逻辑----");
                                    return ;
                                }
                            }
                            String cmsJudItemName = cmsJudItem.getItemStr1();
                            isDownloadFile  = ftpClientForMount.downloadFile(cmsJudItemName+".pdf",FTPPath,downArr);
                            //如果下载成功
                            if (isDownloadFile){
                                FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
                                String fastDfSUrl = fastDFSClient.uploadFile(downArr+"/"+cmsJudItemName+".pdf",".pdf");
                                if(StringUtils.isNotBlank(fastDfSUrl)){
                                    String fastDfsUrl = cmsJudItem.getItemStr2();
                                    if(StringUtils.isNotBlank(fastDfsUrl)){
                                        //证明已经上传成功
                                        fastDFSClient.deleteFile(fastDfsUrl.replace(IMAGE_SERVER_URL,""));
                                    }
                                    //删除本地保存的文件
                                    downFile = new File(downArr+"/"+cmsJudItemName+".pdf");
                                    if(downFile.exists()){
                                        downFile.delete();
                                    }
                                    String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;
                                    cmsJudItem.setItemStr2(imagesUrl);
                                    cmsJudItem.setItemStr3("1");
                                    volAndItemService.updateItemByPrimaryKeySelective(cmsJudItem);
                                }
                            }
                        }
                        break;
                    //如果是件
                    case VolItemConstant.FILE_TYPE_ITEM:
                        CmsJudItem cmsJudItem = volAndItemService.selectByItemId(MathUtils.string2long(fileId));
                        String cmsJudItemName = cmsJudItem.getItemStr1();
                        if(ftpClientForMount.ftpClient==null||!ftpClientForMount.ftpClient.isConnected()){
                            isConnect = ftpClientForMount.initFTPClient();
                            if(!isConnect){
                                logger.info("----FTP连接失败，终止下载逻辑----");
                                return ;
                            }
                        }
                        isDownloadFile  = ftpClientForMount.downloadFile(cmsJudItemName+".pdf",FTPPath,downArr);
                        //如果下载成功
                        if (isDownloadFile){
                            FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
                            String fastDfSUrl = fastDFSClient.uploadFile(downArr+"/"+cmsJudItemName+".pdf",".pdf");
                            if(StringUtils.isNotBlank(fastDfSUrl)){
                                String fastDfsUrl = cmsJudItem.getItemStr2();
                                if(StringUtils.isNotBlank(fastDfsUrl)){
                                    fastDFSClient.deleteFile(fastDfsUrl.replace(IMAGE_SERVER_URL,""));

                                }
                                //删除本地保存的文件
                                downFile = new File(downArr+"/"+cmsJudItemName+".pdf");
                                if(downFile.exists()){
                                    downFile.delete();
                                }
                                cmsJudItem.setItemStr3("1");
                                String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;
                                cmsJudItem.setItemStr2(imagesUrl);
                                volAndItemService.updateItemByPrimaryKeySelective(cmsJudItem);
                            }
                        }
                        break;
                    //如果是单件批量
                    case VolItemConstant.FILE_TYPE_SIN_ITEM:
                        String[] volIds = fileId.split(",");
                        List<CmsSinItem> cmsSinItems = cmsSinItemService.selectSimItemsByIds(Arrays.asList(volIds));
                        for (CmsSinItem cmsSinItem : cmsSinItems){
                            if(ftpClientForMount.ftpClient==null||!ftpClientForMount.ftpClient.isConnected()){
                                isConnect = ftpClientForMount.initFTPClient();
                                if(!isConnect){
                                    logger.info("----FTP连接失败，终止下载逻辑----");
                                    return ;
                                }
                            }
                            String cmsSinItemName = cmsSinItem.getItemStr1();
                            isDownloadFile  = ftpClientForMount.downloadFile(cmsSinItemName+".pdf",FTPPath,downArr);
                            //如果下载成功
                            if (isDownloadFile){
                                FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
                                String fastDfSUrl = fastDFSClient.uploadFile(downArr+"/"+cmsSinItemName+".pdf",".pdf");
                                if (StringUtils.isNotBlank(fastDfSUrl)){
                                    String fastDfsUrl = cmsSinItem.getItemStr2();
                                    if(StringUtils.isNotBlank(fastDfsUrl)){
                                        fastDFSClient.deleteFile(fastDfsUrl.replace(IMAGE_SERVER_URL,""));
                                    }
                                    //删除本地保存的文件
                                    downFile = new File(downArr+"/"+cmsSinItemName+".pdf");
                                    if(downFile.exists()){
                                        downFile.delete();
                                    }
                                    cmsSinItem.setItemStr3("1");
                                    String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;
                                    cmsSinItem.setItemStr2(imagesUrl);
                                    cmsSinItemService.updateSinItemByPrimaryKeySelective(cmsSinItem);
                                }
                            }

                        }
                        break;
                    default:
                }
            }else{
                //本地文件上传
                File localFile = new File(localAddress);
                //文件名：文件地址
                Map<String,String> resultMap = new HashMap<>();
                if(localFile.exists()){
                    ergodicFile(localFile,resultMap);
                }
                //文件地址
                String filePath = null;
                switch (type){
                    //如果是卷
                    case VolItemConstant.FILE_TYPE_VOL:
                        String[] ids = fileId.split(",");
                        List<CmsJudItem> cmsJudItems = volAndItemService.selectAllByVolIds(Arrays.asList(ids));
                        String cmsJudItemName = "";
                        for (CmsJudItem cmsJudItem : cmsJudItems){
                            cmsJudItemName = cmsJudItem.getItemStr1();
                            if (resultMap.containsKey(cmsJudItemName)){
                                filePath = resultMap.get(cmsJudItemName);
                                uploadFastDfsAndUpItem(cmsJudItem,filePath,cmsJudItemName);
                            }
                        }
                        break;
                    //如果是件
                    case VolItemConstant.FILE_TYPE_ITEM:
                        CmsJudItem cmsJudItem = volAndItemService.selectByItemId(MathUtils.string2long(fileId));
                        cmsJudItemName = cmsJudItem.getItemStr1();
                        if (resultMap.containsKey(cmsJudItemName)){
                            filePath = resultMap.get(cmsJudItemName);
                            uploadFastDfsAndUpItem(cmsJudItem,filePath,cmsJudItemName);
                        }
                        break;
                    //如果是单件批量
                    case VolItemConstant.FILE_TYPE_SIN_ITEM:
                        String[] volIds = fileId.split(",");
                        List<CmsSinItem> cmsSinItems = cmsSinItemService.selectSimItemsByIds(Arrays.asList(volIds));
                        String cmsSinItemName = "";
                        for (CmsSinItem cmsSinItem : cmsSinItems){
                            cmsSinItemName = cmsSinItem.getItemStr1();
                            if (resultMap.containsKey(cmsSinItemName)){
                                filePath = resultMap.get(cmsSinItemName);
                                uploadFastDfsAndUpSinItem(cmsSinItem,filePath,cmsSinItemName);
                            }
                        }
                        break;
                    default:
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            userUploadStatus.put(userName,new Date());
        }
    }

    /**
     * @author:zyp
     * @description 遍历本地文件夹，获取所有的文件
     * @date: 2019/6/21 14:29
     * @return
     */
    private static void ergodicFile(File localFile,Map<String,String> resultMap){
        if(localFile.isDirectory()){
            File[] files = localFile.listFiles();
            for(File file : files){
                ergodicFile(file,resultMap);
            }
        }else{
            if(localFile.getName().lastIndexOf(".")!=-1){
                String localFileName = localFile.getName().substring(0,localFile.getName().lastIndexOf("."));
                resultMap.put(localFileName,localFile.getPath());
            }else{
                resultMap.put(localFile.getName(),localFile.getPath());
            }
        }
    }

    /**
     * @author:zyp
     * @description 上传到fastDfs中,并修改件表状态 公共方法
     * @date: 2019/6/21 16:24
     * @return 
     */
    public void uploadFastDfsAndUpItem(CmsJudItem cmsJudItem,String filePath,String cmsJudItemName) throws Exception {
        // 取扩展名
        String originalFilename = filePath.substring(filePath.lastIndexOf(File.separator)+1);
        String extName = "";
        String fileNameNotExt = "";
        if(originalFilename.lastIndexOf(".")==-1){
            fileNameNotExt = originalFilename;
            extName = "pdf";
        }else{
            extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //去掉扩展名的文件名
            fileNameNotExt = originalFilename.substring(0,originalFilename.lastIndexOf("."));
        }
        String itemAdress = cmsJudItem.getItemStr2();
        String IMAGE_SERVER_URL = properties.getProperty("IMAGE_SERVER_URL");
        VolAndItemService volAndItemService = (VolAndItemService) ApplicationContextUtil.getBean(VolAndItemService.class);
        logger.error("表数据文件信息："+cmsJudItemName + "----现实文件信息："+fileNameNotExt);
        if(StringUtils.isNotBlank(cmsJudItemName)&&cmsJudItemName.equals(fileNameNotExt)){
            //如果地址不为空的话就不需要重新上传----此处待定
//            if(StringUtils.isBlank(itemAdress)){
            FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
            String fastDfSUrl = fastDFSClient.uploadFile(filePath,extName);
            logger.error("上传到fastDFSurl的地址："+fastDfSUrl);
            if (StringUtils.isNotBlank(fastDfSUrl)){
                String fastDfsUrl = cmsJudItem.getItemStr2();
                if(StringUtils.isNotBlank(fastDfsUrl)){
                    fastDFSClient.deleteFile(fastDfsUrl.replace(IMAGE_SERVER_URL,""));
                }
                String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;
                cmsJudItem.setItemStr3("1");
                cmsJudItem.setItemStr2(imagesUrl);
                logger.error("插入数据库："+cmsJudItem.getItemId());
                volAndItemService.updateItemByPrimaryKeySelective(cmsJudItem);
            }
//            }
        }
    }

    /**
     * @author:zyp
     * @description 上传到fastDfs中,并修改单件表状态 公共方法
     * @date: 2019/3/27 10:05
     * @return
     */
    public void uploadFastDfsAndUpSinItem(CmsSinItem cmsSinItem,String filePath,String cmsJudItemName) throws Exception {
        // 取扩展名
        String originalFilename = filePath.substring(filePath.lastIndexOf(File.separator)+1);
        String extName = "";
        String fileNameNotExt = "";
        if(originalFilename.lastIndexOf(".")==-1){
            fileNameNotExt = originalFilename;
            extName = "pdf";
        }else{
            extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //去掉扩展名的文件名
            fileNameNotExt = originalFilename.substring(0,originalFilename.lastIndexOf("."));
        }
        String itemAdress = cmsSinItem.getItemStr2();
        String IMAGE_SERVER_URL = properties.getProperty("IMAGE_SERVER_URL");
        CmsSinItemService cmsSinItemService = (CmsSinItemService) ApplicationContextUtil.getBean(CmsSinItemService.class);
        if(StringUtils.isNotBlank(cmsJudItemName)&&cmsJudItemName.equals(fileNameNotExt)){
            //如果地址不为空的话就不需要重新上传----此处待定
//        if(StringUtils.isBlank(itemAdress)){
            FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
            String fastDfSUrl = fastDFSClient.uploadFile(filePath,extName);
            if (StringUtils.isNotBlank(fastDfSUrl)){
                String fastDfsUrl = cmsSinItem.getItemStr2();
                if(StringUtils.isNotBlank(fastDfsUrl)){
                    fastDFSClient.deleteFile(fastDfsUrl.replace(IMAGE_SERVER_URL,""));
                }
                String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;
                cmsSinItem.setItemStr3("1");
                cmsSinItem.setItemStr2(imagesUrl);
                cmsSinItemService.updateSinItemByPrimaryKeySelective(cmsSinItem);
            }
//        }
        }
    }

    public String getFTPIp() {
        return FTPIp;
    }

    public void setFTPIp(String FTPIp) {
        this.FTPIp = FTPIp;
    }

    public String getFTPUser() {
        return FTPUser;
    }

    public void setFTPUser(String FTPUser) {
        this.FTPUser = FTPUser;
    }

    public String getFTPPassword() {
        return FTPPassword;
    }

    public void setFTPPassword(String FTPPassword) {
        this.FTPPassword = FTPPassword;
    }

    public String getFTPPath() {
        return FTPPath;
    }

    public void setFTPPath(String FTPPath) {
        this.FTPPath = FTPPath;
    }

    public String getLocalAddress() {
        return localAddress;
    }

    public void setLocalAddress(String localAddress) {
        this.localAddress = localAddress;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getFTPPort() {
        return FTPPort;
    }

    public void setFTPPort(String FTPPort) {
        this.FTPPort = FTPPort;
    }
}